﻿using System;
using System.Windows.Forms;
using Database;

namespace PassControl
{
    public partial class ControlForm : Form
    {
        public ControlForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DatabaseHelper.Connect();
            turnstileIn.KeyDown += new System.Windows.Forms.KeyEventHandler(inTextboxOnKeyDownHandler);
            turnstileOut.KeyDown += new System.Windows.Forms.KeyEventHandler(outTextboxOnKeyDownHandler);
        }

        private void DisplayUserInfo(TextBox userIdTextBox, ref PictureBox photo, ref Label name, ref Label dorm,
                                     ref Label passType, ref Label permission, ref Label permissionIndicator)
        {
            string passNumber = userIdTextBox.Text;

            Person person = DatabaseHelper.GetPerson(passNumber);

            photo.Image = person.Image;
            name.Text = person.GetFullName();

            Pass pass = DatabaseHelper.GetPass(passNumber);

            dorm.Text = pass.GetDorm();
            passType.Text = pass.GetPassType();
            permission.Text = pass.GetPermission() ? "проход разрешен" : "проход запрещен";
            permissionIndicator.Text = pass.GetPermission() ? "" : "X";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DisplayUserInfo(turnstileIn, ref photoIn, ref nameIn, ref dormIn, ref passTypeIn, ref inPermissionLabel, ref inPermissionIndicator);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DisplayUserInfo(turnstileOut, ref photoOut, ref nameOut, ref dormOut, ref passTypeOut, ref outPermissionLabel, ref outPermissionIndicator);
        }

        private void ControlForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            DatabaseHelper.Disconnect();
        }
        private void inTextboxOnKeyDownHandler(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DisplayUserInfo(turnstileIn, ref photoIn, ref nameIn, ref dormIn, ref passTypeIn, ref inPermissionLabel, ref inPermissionIndicator);
            }
        }
        private void outTextboxOnKeyDownHandler(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DisplayUserInfo(turnstileOut, ref photoOut, ref nameOut, ref dormOut, ref passTypeOut, ref outPermissionLabel, ref outPermissionIndicator);
            }
        }
    }
}
